<?php
/**
 * Created by PhpStorm.
 * User: jwb
 * Date: 2020/5/12
 * Time: 16:37
 */

namespace App\Repositories;

use App\Repositories\Eloquent\Repository;
use App\Traits\SystemCodeTrait;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;

abstract class BaseApplyRepository extends Repository
{
    use SystemCodeTrait;

    public function getNewCode($type = ''): string
    {
        $pre = $type ?: config('app.uuid_prefix', 'SN');
        $uuid = $this->model->whereDate('created_at', '=', date('Y-m-d'))->orderByDesc('id')->value('uuid');
        if (!$uuid) {
            $code = date('Ymd') . str_pad(1, 4, 0, STR_PAD_LEFT);
        } else {
            $code = substr($uuid, -12) + 1;
        }
        return $pre . $code;
    }

    public function formPublic(Form $form, $role = 0)
    {
        $form->hidden('review_remark');
        $form->hidden('dept_review_status');
        $form->hidden('review_status');
        if ($form->isCreating()) {
            $form->hidden('uuid', __('编号'));
            $form->hidden('serial_number')->default(0);
            $form->hidden('year')->default(date('Y'));

            $form->hidden('department_id');
            $form->hidden('user_id', __('用户ID'));
        }
        $this->formSaving($form, $role);
    }

    public function formSaving(Form $form, $role = 0)
    {
        $user = Admin::user();
        $form->saving(function (Form $form) use ($user) {
            if ($form->isCreating()) {
                $form->year = date('Y');
                $form->serial_number = $this->getSerialNumber($form->year);
                $form->uuid = $this->getApplyNewCode($form->year, $form->serial_number);
                if (!$form->user_id) {
                    $form->user_id = $user->id;
                }
                if (!$form->department_id) {
                    $form->department_id = $user->department_id;
                }
            }
            if (!$user['role_type']) {
                $form->review_status = 0;
                $form->dept_review_status = 0;
            } elseif (in_array($user['role_type'], [1, 2])) {
                $form->review_status = 0;
                $form->dept_review_status = 1;
            }
        });
    }
}
